package tech.popsoft.cip.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.popsoft.cip.message.common.enums.IntegrationModelEnum;
import tech.popsoft.cip.manage.service.ApiAppService;
import tech.popsoft.cip.manage.service.ApiMessagePermissionService;
import tech.popsoft.cip.manage.service.ApiServicePermissionService;
import tech.popsoft.platform.common.base.BaseServiceImpl;
import tech.popsoft.platform.common.enums.StatusEnum;
import tech.popsoft.platform.common.exception.CommonException;
import tech.popsoft.platform.common.exception.CustomException;
import tech.popsoft.cip.manage.entity.ApiApp;
import tech.popsoft.cip.manage.entity.ApiMessagePermission;
import tech.popsoft.cip.manage.entity.ApiServicePermission;
import tech.popsoft.cip.manage.exception.AppExceptionEnum;
import tech.popsoft.cip.manage.mapper.ApiAppMapper;

import java.util.List;
import java.util.UUID;

/**
 * 应用 服务实现类
 * @author wqliu
 * @date 2021-08-17
 *
 */
@Service
public class ApiAppServiceImpl extends BaseServiceImpl<ApiAppMapper, ApiApp> implements ApiAppService {
    @Autowired
    private ApiServicePermissionService apiServicePermissionService;

    @Autowired
    private ApiMessagePermissionService apiMessageTopicPermissionService;

    @Override
    public ApiApp init() {
        ApiApp entity=new ApiApp();
        entity.setStatus(StatusEnum.NORMAL.name());
        entity.setIntegrationModel(IntegrationModelEnum.CLIENT.name());
        //创建应用时自动生成密钥
        entity.setSecret(UUID.randomUUID().toString());
        return entity;
    }

    @Override
    public void enable(String id) {
        ApiApp entity = getEntity(id);
        entity.setStatus(StatusEnum.NORMAL.name());
        modify(entity);
    }

    @Override
    public void disable(String id) {
        ApiApp entity = getEntity(id);
        entity.setStatus(StatusEnum.DEAD.name());
        modify(entity);
    }

    @Override
    public void resetSecret(String id) {
        ApiApp entity = getEntity(id);
        entity.setSecret(UUID.randomUUID().toString());
        modify(entity);
    }

    @Override
    public void authorize(String appCode, String appSecret) {
        List<ApiApp> list = this.lambdaQuery().eq(ApiApp::getCode, appCode)
               .list();
        if(CollectionUtils.isEmpty(list)){
            throw new CustomException(AppExceptionEnum.APP_CODE_OR_SECRET_ERROR);
        }else {
            ApiApp apiApp = list.get(0);
            String secret = apiApp.getSecret();
            BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
            if(!encoder.matches(secret,appSecret)){
                throw new CustomException(AppExceptionEnum.APP_CODE_OR_SECRET_ERROR);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void grantApiPermission(String appId, List<String> apiServiceIdList) {

        if(CollectionUtils.isNotEmpty(apiServiceIdList)) {
            //移除末尾空元素
            apiServiceIdList.removeIf(x-> StringUtils.isEmpty(x));

            for (String apiServiceId : apiServiceIdList) {
                //查询是否已存在授权记录
                int count = apiServicePermissionService.lambdaQuery().eq(ApiServicePermission::getAppId, appId)
                        .eq(ApiServicePermission::getServiceId, apiServiceId).count();
                //不存在时授权
                if(count==0){
                    ApiServicePermission entity=new ApiServicePermission();
                    entity.setAppId(appId);
                    entity.setServiceId(apiServiceId);
                    apiServicePermissionService.add(entity);
                }

            }
        }
    }

    @Override
    public void withdrawApiPermission(String appId, List<String> apiServiceIdList) {
        if(CollectionUtils.isNotEmpty(apiServiceIdList)) {
            QueryWrapper<ApiServicePermission> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(ApiServicePermission::getAppId, appId)
                    .in(ApiServicePermission::getServiceId, apiServiceIdList);
            apiServicePermissionService.remove(queryWrapper);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void grantMessageTopicPermission(String appId, List<String> apiMessageTopicIdList) {

        if(CollectionUtils.isNotEmpty(apiMessageTopicIdList)) {
            //移除末尾空元素
            apiMessageTopicIdList.removeIf(x-> StringUtils.isEmpty(x));

            for (String apiMessageTopicId : apiMessageTopicIdList) {
                //查询是否已存在授权记录
                int count = apiMessageTopicPermissionService.lambdaQuery().eq(ApiMessagePermission::getAppId, appId)
                        .eq(ApiMessagePermission::getMessageTopicId, apiMessageTopicId).count();
                //不存在时授权
                if(count==0){
                    ApiMessagePermission entity=new ApiMessagePermission();
                    entity.setAppId(appId);
                    entity.setMessageTopicId(apiMessageTopicId);
                    apiMessageTopicPermissionService.add(entity);
                }

            }
        }
    }

    @Override
    public void withdrawMessageTopicPermission(String appId, List<String> apiMessageTopicIdList) {
        if(CollectionUtils.isNotEmpty(apiMessageTopicIdList)) {
            QueryWrapper<ApiMessagePermission> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(ApiMessagePermission::getAppId, appId)
                    .in(ApiMessagePermission::getMessageTopicId, apiMessageTopicIdList);
            apiMessageTopicPermissionService.remove(queryWrapper);
        }
    }



    @Override
    public void beforeAdd(ApiApp entity) {


        //验证编码全局唯一
        QueryWrapper<ApiApp> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApiApp::getCode, entity.getCode());
        int count = count(queryWrapper);
        if (count > 0) {
            throw new CustomException(CommonException.CODE_EXIST);
        }


        //验证名称全局唯一
        queryWrapper.lambda().eq(ApiApp::getName, entity.getName());
        count = count(queryWrapper);
        if (count > 0) {
            throw new CustomException(CommonException.NAME_EXIST);
        }


    }

    @Override
    public void beforeModify(ApiApp entity) {


        //验证编码全局唯一
        QueryWrapper<ApiApp> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApiApp::getCode, entity.getCode())
            .ne(ApiApp::getId,entity.getId());
        int count = count(queryWrapper);
        if (count > 0) {
            throw new CustomException(CommonException.CODE_EXIST);
        }


        //验证名称全局唯一
        queryWrapper.lambda().eq(ApiApp::getName, entity.getName())
                .ne(ApiApp::getId,entity.getId());
        count = count(queryWrapper);
        if (count > 0) {
            throw new CustomException(CommonException.NAME_EXIST);
        }


    }


    @Override
    public String getIntegrationModelByAppCode(String appCode) {
        return getByCode(appCode).getIntegrationModel();

    }

    @Override
    public ApiApp getByCode(String code) {
        List<ApiApp> list = this.lambdaQuery().eq(ApiApp::getCode, code).list();
        if(CollectionUtils.isNotEmpty(list)){
            return list.get(0);

        }else{
            throw new CustomException(AppExceptionEnum.APP_CODE_NOT_EXIST);
        }
    }

}
